package mybatis;

import java.lang.reflect.Field;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;

/**
 * 〈〉
 *
 * @author coach tam
 * @email 327395128@qq.com
 * @create 2023/10/17
 * @since 1.0.0
 * 〈坚持灵活 灵活坚持〉
 */
public class StudentMapperImpl implements BaseMapper<Student> {
    private Class<?> entityClass;

    private String selectSql;


    public StudentMapperImpl() {
        Type t = getClass().getGenericInterfaces()[0];
        Type firType = ((ParameterizedType) t).getActualTypeArguments()[0];
        try {
            entityClass = (Class<?>) firType;
        } catch (ClassCastException e) {
            e.printStackTrace();
        }
        String tableName = getTableName();
        String columns = getColumns();
        selectSql = "select " + columns + " from " + tableName;
    }

    private String getTableName() {
        TableName annotation = entityClass.getAnnotation(TableName.class);
        String tableName = null;
        if (annotation == null) {
            tableName = entityClass.getName();
        }
        tableName = annotation.value();
        return tableName;
    }

    private String getColumns() {
        StringBuilder sb = new StringBuilder();

        // 获取类中所有字段
        Field[] fields = entityClass.getDeclaredFields();
        for (Field field : fields) {
            // 检查字段上是否有@TableField注解
            if (field.isAnnotationPresent(TableField.class)) {
                TableField tableFieldAnnotation = field.getAnnotation(TableField.class);
                String fieldName = tableFieldAnnotation.value();
                sb.append(fieldName).append(",");
            }
        }

        // 移除最后一个逗号
        if (sb.length() > 0) {
            sb.deleteCharAt(sb.length() - 1);
        }

        String result = sb.toString();
        return result;
    }

    @Override
    public Student selectOne(QueryWrapper<Student> queryWrapper) {
        System.out.println(selectSql + " " + queryWrapper.whereSql());
        return new Student();
    }

}
